package com.onetech.adrewards.free.models;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.json.JSONArray;
import org.json.JSONObject;

import android.os.Bundle;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.onetech.adrewards.free.OneTech_ApplicationContext;
import com.onetech.adrewards.free.config.AppConfig.Cache;
import com.onetech.adrewards.free.config.AppConfig.URLRequestApi;
import com.onetech.adrewards.free.http.APIRequestResult;
import com.onetech.adrewards.free.http.ZuZuHttpRequest;
import com.onetech.adrewards.free.listener.NewsIF;
import com.onetech.adrewards.free.objects.NewsDTO;
import com.onetech.adrewards.free.utils.AdrewadsUtils;
import com.zuzu.db.store.SimpleStoreIF;

public class NewsModel implements NewsIF {
	private static NewsIF _instance;
	private static final Lock createLock = new ReentrantLock();
	private static final int STORE_EXPIRE = 10 * 60;
	public NewsModel() {
		getStoreAdapter();
	}

	public static NewsIF getInstance() {
		if (_instance == null) {
			createLock.lock();
			if (_instance == null) {
				_instance = new NewsModel();
			}
			createLock.unlock();
		}
		return _instance;
	}
	private SimpleStoreIF getStoreAdapter() {
		return AdrewadsUtils.getStoreAdapter(Cache.ADREWARD_NAME,
				OneTech_ApplicationContext.getContext(), Cache.ADREWARD_NUMBER);
	}
	public void setStore(String key, Object item) {
		if (item == null) {
			return;
		}
		Gson gson = new Gson();
		String temp = gson.toJson(item);
		this.getStoreAdapter().put(key, temp, STORE_EXPIRE);
	}
	@SuppressWarnings("unchecked")
	private List<NewsDTO> deserializeInteger(String json) {
		List<NewsDTO> result = null;
		if (json == null || json.equals(""))
			return result;
		try {
			result = new ArrayList<NewsDTO>();
			Gson gson = new Gson();
			Type listType = new TypeToken<List<NewsDTO>>() {
			}.getType();
			result = (List<NewsDTO>) gson.fromJson(json, listType);
		} catch (Exception e) {
			return null;
		}
		return result;
	}
	@Override
	public List<NewsDTO> getListNews(String page) {
		
		try {
			List<NewsDTO> data=null;
			
			String json=getStoreAdapter().get(Cache.NEWS_PAGE_KEY+page);
			if(json!=null){
				data=deserializeInteger(json);
			}
			if(data!=null && data.size()>0){
				return data;
			}
			Bundle params = new Bundle();
			APIRequestResult result = ZuZuHttpRequest.getInstance()
					.getDataFromServer(URLRequestApi.GET_NEWS_URL+page, params);
			data=parserListNewsFromAPIResult(result);
			if(data!=null && data.size()>0){
				setStore(Cache.NEWS_PAGE_KEY+page, data);
			}
			return data;
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public NewsDTO getNewsDetail(String newsId) {
		Bundle params = new Bundle();
		APIRequestResult result = ZuZuHttpRequest.getInstance()
				.getDataFromServer(URLRequestApi.GET_NEWS_URL, params);
		return parserNewsFromAPIResult(result);
	}

	private List<NewsDTO> parserListNewsFromAPIResult(APIRequestResult data) {
		try {
			List<NewsDTO> result = null;

			if (data.error_code.equals("0") && data.data != null
					&& !data.data.equals("")) {
				JSONObject jsonObject=(JSONObject)data.data;
				JSONArray jArr = jsonObject.getJSONArray("result");
				if (jArr != null && jArr.length() >= 0) {
					result = new ArrayList<NewsDTO>();
					for (int i = 0; i < jArr.length(); i++) {
						JSONObject jb = jArr.getJSONObject(i);
						NewsDTO item = parserNewsFromJSONObject(jb);
						if (item != null) {
							result.add(item);
						}
					}

				}
			}
			return result;
		} catch (Exception e) {
			return null;
		}
	}

	private NewsDTO parserNewsFromAPIResult(APIRequestResult data) {
		try {
			NewsDTO result = null;

			if (data.error_code.equals("0") && data.data != null
					&& !data.data.equals("")) {
				JSONObject jsonObject=(JSONObject)data.data;
				JSONArray jArr = jsonObject.getJSONArray("result");
				if (jArr != null && jArr.length() >= 0) {
					result = new NewsDTO();
					JSONObject jb = jArr.getJSONObject(0);
					if (jb != null) {
						result = parserNewsFromJSONObject(jb);
					}
				}
			}
			return result;
		} catch (Exception e) {
			return null;
		}
	}

	private NewsDTO parserNewsFromJSONObject(JSONObject data) {
		try {
			NewsDTO result = new NewsDTO();
			result.setContents(data.getString("contents"));
			//result.setCreator(data.getString("creator"));
			result.setId(data.getString("id"));
			//result.setStatus(data.getString("status"));
			result.setTitle(data.getString("title"));
			//result.setUpdated_at(data.getString("updated_at"));
			String date=AdrewadsUtils.dateFormat(data.getString("created_at"));
			result.setCreated_at(date);
			
			return result;
		} catch (Exception e) {
			return null;
		}
	}
}
